﻿using System.Collections.Generic;
using Gp.Scripts.Core;
using Pathfinding;
using QFramework;
using Shapes;
using Sirenix.OdinInspector;
using UnityEngine;

namespace Gp.Scripts.GUI
{
    public class SkillAreaIndicator : MonoBehaviour
    {
        [LabelText("半径")] [SerializeField] private int testRadius = 1;
        [LabelText("弧度")] [SerializeField] private int radian = 2;
        [SerializeField] private float gridSize = 1;


        [HideInInspector] [SerializeField] private Transform container;
        [SerializeField] private Rectangle quadPrefab;
        [SerializeField] private Polyline linePrefab;


        [SerializeField] private Color highlightColor;
        [SerializeField] private Color normalColor;
        private readonly List<Rectangle> _rectangles = new();
        private readonly Queue<Rectangle> _pool = new();


        public void DrawCells(IEnumerable<VBattleCell> points)
        {
            HashSet<VBattleCell> set = new();
            if (container == null)
            {
                container = new GameObject("container").transform;
                container.SetParent(transform, false);
                // container.transform.rotation = Quaternion.Euler(90, 0, 0);
            }
            
            ClearAll();
            foreach (var p in points)
            {
                var rect = CreateRectangle();
                SnapToGrid(p, rect.transform);
                MarkHighlight(rect);
                
                // foreach (var n in p.Node.GetNeighbours())
                // {
                //     set.Add(new VBattleCell(n));
                // }
            }


            foreach (var n in set)
            {
                var rect = CreateRectangle();
                SnapToGrid(n, rect.transform);
                MarkNormal(rect);
            }
        }

        private void SnapToGrid(VBattleCell node, Transform obj, float heightOffset = .02f)
        {
            var resPos = node.Position;
            obj.transform.rotation = Quaternion.Euler(90, 0, 0);
            resPos.y += heightOffset;
            obj.position = resPos;
        }


        private void MarkHighlight(ShapeRenderer rect)
        {
            rect.Color = highlightColor;
        }

        private void MarkNormal(ShapeRenderer rect)
        {
            rect.Color = normalColor;
        }


        public void ClearAll()
        {
            foreach (var rect in _rectangles)
            {
                rect.Hide();
                _pool.Enqueue(rect);
            }

            _rectangles.Clear();
        }


        private Rectangle CreateRectangle()
        {
            Rectangle res = null;
            if (_pool.Count > 0)
            {
                res = _pool.Dequeue();
            }
            else
            {
                res = Instantiate(quadPrefab, container, false);
            }

            _rectangles.Add(res);
            res.Show();
            
            return res;
        }
    }
}